#define  _CRT_SECURE_NO_WARNINGS 1
#include"Heap.h"

void Swap(DataType* e1, DataType* e2)
{
	DataType tmp = *e1;
	*e1 = *e2;
	*e2 = tmp;
}
void AdjustDown(DataType* arr, int size, int parent)
{
	int child = parent * 2 + 1;
	while (child < size)
	{
		if (child + 1 < size && arr[child + 1] < arr[child])
		{
			child++;
		}
		else if (arr[child] < arr[parent])
		{
			Swap(&arr[child], &arr[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}
void AdjustUp(DataType* arr, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (arr[child] > arr[parent])
		{
			Swap(&arr[child], &arr[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void AdjustUp(DataType* arr, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (arr[child] > arr[parent])
		{
			Swap(&arr[child], &arr[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void HeapPrint(Heap* hp)
{
	assert(hp);
	for (int i = 0; i < hp->size; i++)
	{
		printf("%d", hp->arr[i]);
	}
	printf("\n");
}
void HeapInit(Heap* hp)
{
	assert(hp);
	for (int i = 0; i < hp->size; i++)
	{
		printf("%d", hp->arr[i]);
	}
	printf("\n");
}
void HeapInit(Heap* hp)
{
	assert(hp);
	hp->arr = NULL;
	hp->size = 0;
	hp->capacity = 0;
}
void HeapDestroy(Heap* hp)
{
	assert(hp);
	free(hp->arr);
	hp->arr = NULL;
	hp->capacity = hp->size = 0;
}
void HeapPush(Heap* hp, DataType x)
{
	assert(hp);
	if (hp->capacity == hp->size)
	{
		int newcapacity = hp->capacity == 0 ? 4 : hp->capacity * 2;
		DataType* tmp = (DataType*)realloc(hp->arr, sizeof(DataType) * newcapacity);
		if (tmp == NULL)
		{
			printf("realloc is fail\n");
			exit(-1);
		}
		hp->arr = tmp;
		hp->capacity = newcapacity;
	}
	hp->arr[hp->size] = x;
	hp->size++;

	AdjustUp(hp->arr, hp->size - 1);
}
DataType HeapTop(Heap* hp)
{
	assert(hp);
	assert(hp->size > 0);
	return hp->arr[0];
}
DataType HeapTop(Heap* hp)
{
	assert(hp);
	assert(hp->size > 0);
	return hp->arr[0];
}
void HeapPop(Heap* hp)
{
	assert(hp);
	assert(hp->size > 0);
	Swap(&hp->arr[hp->size - 1], &hp->arr[0]);
	hp->size--;

	AdjustDown(hp->arr, hp->size, 0);
}
void HeapPop(Heap* hp)
{
	assert(hp);
	assert(hp->size > 0);
	Swap(&hp->arr[hp->size - 1], &hp->arr[0]);
	hp->size--;

	AdjustDown(hp->arr, hp->size, 0);
}
bool HeapEMpty(Heap* hp)
{
	assert(hp);
	return hp->size == 0;
}
int HeapSize(Heap* hp)
{
	assert(hp);
	return hp->size;
}
int HeapSize(Heap* hp)
{
	assert(hp);
	return hp->size;
}